﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using AttributeRouting;
using AttributeRouting.Web.Mvc;
using Newtonsoft.Json.Linq;
using PH.Model.Results;
using PH.Model.Accounts;
using PH.Logic.Accounts;
using PH.Logic.Services;
using PH.Model.Services;
namespace PH.Web.Management.Areas.Services.Controllers
{
    [RouteArea("Services")]
    [RoutePrefix("ByUser")]
    public class ByUserApiController : ServiceBase
    {
        [Route("Login")]
        [HttpPost]
        public JsonEntity<UserTokenModel> Login(JObject request)
        {
            var errinfo = "登陆失败，原因：";
            try
            {
                base.Authorize();
                var userName = request.Value<string>("userName");
                var password = request.Value<string>("password");
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) throw new Utils.PhException("请提供用户名和密码");

                var user = UserLogic.GetUser(userName, true);
                if (user != null)
                {
                    var token = UserTokenLogic.CreateNew(new Model.Services.UserTokenModel() { UGuid = user.Guid });
                    return new JsonEntity<UserTokenModel>(token);
                }
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<UserTokenModel>(null, errinfo, false);
        }
        [Route("GetUser")]
        [HttpPost]
        public JsonEntity<UserModel> GetUser(JObject request)
        {
            var errinfo = "登陆失败，原因：";
            try
            {
                base.Authorize();
                var user = base.GetUserByToken(request);
                if (user!=null)
                    return new JsonEntity<UserModel>(user);
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<UserModel>(null, errinfo, false);
        }
    }
}
